package com.xbongbong.saas.service.impl;/*/*/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.help.menu.InitWorkOrderHelp;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.dto.FormEntityAddDTO;
import com.xbongbong.paas.pojo.dto.FormEntityUpdateDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.dto.FormUpdateBatchDTO;
import com.xbongbong.pro.workorder.pojo.WorkOrderTemplateDetailInfoPojo;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderTemplateCategoryModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.service.WorkOrderExplainService;
import com.xbongbong.saas.service.WorkOrderFormService;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 工单form 相关业务service 实现
 * @author 魏荣杰
 * @date 2019/3/18 13:48
 * @since v1.0
 * @version v1.0
 */
@Service("workOrderFormService")
public class WorkOrderFormServiceImpl implements WorkOrderFormService {
    private static final Logger LOG = LoggerFactory.getLogger(WorkOrderFormServiceImpl.class);

    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderExplainService workOrderExplainService;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private InitWorkOrderHelp initWorkOrderHelp;
    @Resource
    private WorkOrderTemplateCategoryModel workOrderTemplateCategoryModel;

    @Override
    public void saveDefaultFormAndExplain(String corpid, String userId, WorkOrderTemplateDetailInfoPojo infoPojo, Long appId, Long templateId) throws XbbException {
        try {
            PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.WORK_ORDER.getAlias(), appId, corpid);
            if (Objects.isNull(paasMenuEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            FormEntityAddDTO formEntityAddDTO = new FormEntityAddDTO();
            WorkOrderFormEntity formEntity = new WorkOrderFormEntity();
            BeanUtil.copyProperties(formEntityAddDTO, formEntity);
            formEntity.setTemplateId(templateId);
            formEntity.setCorpid(corpid);
            formEntity.setAppId(appId);
            formEntity.setMenuId(paasMenuEntity.getId());
            formEntity.setName(infoPojo.getTemplateName());
            formEntity.setNameEn(infoPojo.getTemplateNameEn());
            formEntity.setCustomTitle(JSON.toJSONString(initWorkOrderHelp.getWorkOrderDefaultTitle(XbbRefTypeEnum.WORK_ORDER.getCode())));
            formEntity.setSummary(JSONObject.toJSONString(initWorkOrderHelp.getWorkOrderDefaultSummary(XbbRefTypeEnum.WORK_ORDER.getCode())));
            formEntity.setLabels(JSONObject.toJSONString(initWorkOrderHelp.getWorkOrderDefaultLabel(XbbRefTypeEnum.WORK_ORDER.getCode())));
            formEntity.setAssociationList(JSONObject.toJSONString(formEntityAddDTO.getAssociationList()));
            formEntity.setBusinessRules(formEntityAddDTO.getBusinessRules());
            formEntity.setCoOpPerms(JSONObject.toJSONString(formEntityAddDTO.getCoOpPerms()));
            formEntity.setCreatorId(userId);
            formEntity.setTemplateId(templateId);
            Long now = DateTimeUtil.getInt();
            formEntity.setAddTime(now);
            formEntity.setUpdateTime(now);
            formEntity.setDel(0);
            workOrderFormModel.insert(formEntity);
            workOrderExplainService.saveDefaultExplain(corpid, userId, appId, formEntity.getId(), paasMenuEntity.getId());
        } catch (XbbException e) {
            throw e;
        }
    }

    @Override
    public List<WorkOrderFormEntity> getTemplateWithPermission(UserVO loginUser, Long appId, Integer isFree) {
        return workOrderFormModel.getTemplateWithPermission(loginUser.getCorpid(), loginUser, appId, isFree);
    }


    @Override
    public boolean getFormPermissionByFormId(UserVO loginUser, Long formId) {
        String corpid = loginUser.getCorpid();
        String userId = loginUser.getUserId();
        boolean isBoss = loginUser.isAdminOrBoss();
        boolean maxDataPermission = loginUser.isMaxDataPermission();

        WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
        if (Objects.equals(0, workOrderFormEntityExt.getEnable())) {
            return false;
        }
        WorkOrderTemplateEntity entityExt = workOrderTemplateModel.getBykey(workOrderFormEntityExt.getTemplateId(), corpid);
        if (isBoss || maxDataPermission) {
            return true;
        }

        String scopeRule = entityExt.getScopeRule();
        JSONObject scopeRuleObj =  JSONObject.parseObject(scopeRule);
        String deptStr = scopeRuleObj.getString("dept");
        List<Long> deptList = JSONArray.parseArray(deptStr, Long.class);
        String userStr = scopeRuleObj.getString("user");
        List<String> userList = JSONArray.parseArray(userStr, String.class);
        if ((deptList == null || deptList.size() == 0) && (userList == null || userList.size() == 0)) {
            // 如果没填值就默认全公司
            return true;
        }
        List<String> depUserIdList = new ArrayList<>();
        if (deptList != null && deptList.size() > 0) {
            // 获取子部门的depId
            deptList = departmentModel.getSubDepIdList(corpid, deptList);
            depUserIdList = userModel.getDepUserIdList(corpid, deptList);
        }
        userList.addAll(depUserIdList);
        if (userList.contains(userId)) {
            return true;
        }

        return false;
    }



    @Override
    public void updateBatch(FormUpdateBatchDTO formUpdateBatchDTO) throws XbbException {
        try {
            List<WorkOrderFormEntity> formList = new ArrayList<>();
            if(Objects.nonNull(formUpdateBatchDTO) && Objects.nonNull(formUpdateBatchDTO.getFormList())){
                for(FormEntityUpdateDTO formEntityUpdateDTO: formUpdateBatchDTO.getFormList()) {
                    WorkOrderFormEntity workOrderFormEntity = new WorkOrderFormEntity();
                    BeanUtil.copyProperties(formEntityUpdateDTO, workOrderFormEntity);
                    workOrderFormEntity.setAssociationList(JSONObject.toJSONString(formEntityUpdateDTO.getAssociationList()));
                    long now = DateUtil.getInt();
                    workOrderFormEntity.setUpdateTime(now);
                    formList.add(workOrderFormEntity);
                }
            }
            if(Objects.nonNull(formUpdateBatchDTO) && !formList.isEmpty()){
                String corpid = formUpdateBatchDTO.getCorpid();
                workOrderFormModel.updateBatch(formList, corpid);
            }
        } catch (Exception e) {
            LOG.error("paasForm.updateBatch更新表单信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }
}
